const fs = require('fs');

function copy(o) {
  return JSON.parse(JSON.stringify(o));
}

module.exports = (api) => {
  const cacheApiFile = api.paths.absTmpPath + '/dumi/apis.json';
  api.register({
    key: 'dumi.detectApi',
    fn({ identifier, data }) {
      Object.keys(copy(data)).forEach((key) => {
        data[key] = data[key]
          .filter(
            (i) => (i.description && /^@/.test(i.description)) || i.parsed,
          )
          .map((i) => ({
            ...i,
            parsed: true,
            description: !i.parsed ? i.description.slice(1) : i.description,
          }));
      });
      const apis = fs.existsSync(cacheApiFile) ? require(cacheApiFile) : {};
      apis[identifier] = data;
      const generateApisFile = () => {
        api.writeTmpFile({
          path: 'dumi/apis.json',
          content: JSON.stringify(apis, null, 2),
        });
      };
      generateApisFile();
    },
  });
};
